import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
// 请求拦截器
request.interceptors.request.use(config => {
  // Do something before request is sent
  // console.log(store.getters.token)
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
}, error => {
  // Do something with request error
  return Promise.reject(error)
})
// 响应拦截器

request.interceptors.response.use(response => {
  // Do something before response is sent
  if (response.data instanceof Blob) return response.data
  const { success, data, message } = response.data
  // console.log(response.data)
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, error => {
  // Do something with response error
  if (
    error.response.status === 401
  ) {
    Message.error('登录状态无效，请重新登录')
    store.dispatch('user/logout')
    // 跳转到登录页面
    router.push('/login')
  } else {
    Message({ type: 'error', message: error.message })
  }

  return Promise.reject(error)
})
export default request
